<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      :model="dataForm"
      @keyup.enter.native="getDataList()"
    >
      <el-form-item>
        <el-input
          v-model="dataForm.identifying"
          placeholder="设备的IMEI号码"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="dataForm.carCode"
          placeholder="车牌号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select clearable v-model="dataForm.status" placeholder="GPS状态">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button
          type="danger"
          @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0"
          >批量删除</el-button
        >
        <el-button type="success" @click="downloadTemplate()"
          >下载模板</el-button
        >
        <el-upload
          style="display: inline-block; margin-left: 10px;"
          v-if="isAuth('sys:gps:import')"
          :headers="uploadHeaders"
          :on-change="changeUP"
          :show-file-list="false"
          class="upload-demo up_div"
          :action="baseUrl"
          multiple
          :limit="1"
          :on-success="handleBaseUrlSuccess"
          ref="upload"
        >
          <el-button :loading="loadingUp" type="warning">{{
            loadName
          }}</el-button>
          <!-- <template #tip>
            </template> -->
        </el-upload>
        <el-button type="success" :disabled="isOk" @click="recipientAll()"
          >批量领取</el-button
        >
        <el-button type="primary" @click="downloadBindingExcel()"
          >下载GPS绑定模版</el-button
        >
        <el-upload
          style="display: inline-block; margin-left: 10px;"
          :headers="uploadHeaders"
          :show-file-list="false"
          class="upload-demo up_div"
          :action="baseUrl2"
          multiple
          :limit="1"
          :on-success="batchBindingGPSSuccess"
          ref="upload"
        >
          <el-button type="warning">
            批量绑定
          </el-button>
          <!-- <template #tip>
            </template> -->
        </el-upload>
        <el-button type="success" @click="exportBtn()">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      >
      </el-table-column>
      <el-table-column
        prop="identifying"
        header-align="center"
        align="center"
        label="设备的IMEI号码"
      >
      </el-table-column>
      <el-table-column
        prop="status"
        header-align="center"
        align="center"
        label="GPS状态"
      >
        <template slot-scope="scope">
          {{
            scope.row.status === 0
              ? "未绑定"
              : scope.row.status === 1
              ? "已绑定"
              : scope.row.status === 2
              ? "闲置"
              : scope.row.status === 3
              ? "已领取"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="transportStatus"
        header-align="center"
        align="center"
        label="运输状态"
      >
        <template slot-scope="scope">
          {{
            scope.row.transportStatus === 0
              ? "未运输"
              : scope.row.transportStatus === 1
              ? "运输中"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="carCode"
        header-align="center"
        align="center"
        label="车牌号"
      >
      </el-table-column>
      <el-table-column
        prop="projectName"
        header-align="center"
        align="center"
        label="所属项目"
      >
      </el-table-column>
      <el-table-column
        prop="url"
        header-align="center"
        align="center"
        label="二维码"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px;"
            :src="scope.row.url"
            :preview-src-list="[scope.row.url]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="addOrUpdateHandle(scope.row.id)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
          <el-button
            v-if="
              isAuth('gps:history:receive') &&
                scope.row.transportStatus !== 1 &&
                scope.row.status !== 3
            "
            type="text"
            size="small"
            @click="receiveHandle(scope.row, true)"
            >领取</el-button
          >
          <el-button
            v-if="
              isAuth('gps:history:revert') &&
                scope.row.transportStatus !== 1 &&
                scope.row.status === 3
            "
            type="text"
            size="small"
            @click="receiveHandle(scope.row, false)"
            >归还</el-button
          >
          <el-button
            v-if="isAuth('gps:history:page')"
            type="text"
            size="small"
            @click="historyHandle(scope.row.id)"
            >历史记录</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageParams.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageParams.limit"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getDataList"
    ></add-or-update>
    <!-- 领取归还 -->
    <el-dialog
      :title="isReceive ? '领取' : '归还'"
      :close-on-click-modal="false"
      :visible.sync="visible"
    >
      <el-form
        :model="receiveForm"
        :rules="receiveRule"
        ref="receiveForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="162px"
      >
        <el-form-item :label="isReceive ? '领取人' : '归还人'" prop="recipient">
          <el-input
            v-model="receiveForm.recipient"
            :placeholder="isReceive ? '领取人' : '归还人'"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="receiveForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>

    <!-- 历史记录 -->
    <el-dialog
      title="历史记录"
      :close-on-click-modal="false"
      :visible.sync="historyVisible"
    >
      <HistoryRecord ref="historyRecord" :gpsid="tempid"></HistoryRecord>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from "./gpsManagement-add-or-update";
import HistoryRecord from "./historyRecord.vue";
import Vue from "vue";
export default {
  data() {
    return {
      tempid: "",
      isOk: true,
      isAll: false,
      uploadHeaders: { token: Vue.cookie.get("token") },
      loadingUp: false,
      baseUrl: `${window.SITE_CONFIG["baseUrl"]}/sys/gps/management/importExcel`,
      baseUrl2: `${window.SITE_CONFIG["baseUrl"]}/sys/gps/management/batchBindingGPS`,
      loadName: "导入",
      options: [
        {
          label: "闲置",
          value: 2
        },
        {
          label: "已领取",
          value: 3
        },
        {
          label: "已绑定",
          value: 1
        },
        {
          label: "已解绑",
          value: 0
        }
      ],
      dataForm: {
        carCode: "",
        identifying: "",
        status: null
      },
      dataList: [],
      pageParams: {
        page: 1,
        limit: 10
      },
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      isReceive: true,
      visible: false,
      receiveForm: {
        recipient: "",
        remark: "",
        gpsId: ""
      },
      receiveRule: {
        recipient: [{ required: true, message: "", trigger: "blur" }]
      },
      historyVisible: false
    };
  },
  components: {
    AddOrUpdate,
    HistoryRecord
  },
  activated() {
    this.getDataList();
  },
  methods: {
    // 导出
    exportBtn() {
      this.$http({
        url: this.$http.adornUrl(
          `/sys/gps/management/export?carCode=${this.dataForm.carCode}&identifying=${this.dataForm.identifying}&status=${this.dataForm.status}`
        ),
        method: "get",
        responseType: "blob"
      }).then(({ data }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        let a = document.createElement("a");
        a.download = "导出.xlsx";
        a.href = URL.createObjectURL(blob);
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
      });
    },
    // 历史记录
    historyHandle(id) {
      //打开 dialog框
      this.historyVisible = true;
      //保持gpsid到临时变量 传给子组件
      this.tempid = id;
      this.$nextTick(() => {
        // 调用子组件方法
        this.$refs.historyRecord.getHistoryRecordList(id);
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["receiveForm"].validate(valid => {
        if (valid) {
          // 多个领取
          if (this.dataListSelections.length > 0) {
            this.isAll = true;
            var arrs = this.dataListSelections.map(item => {
              return item.id;
            });
            console.log(arrs, "1111");
          } else {
            this.isAll = false;
          }
          this.$http({
            url: this.$http.adornUrl(
              `/sys/gps/management/${this.isReceive ? "receive" : "revert"}`
            ),
            method: "post",
            data: this.$http.adornData({
              recipient: this.receiveForm.recipient,
              remark: this.receiveForm.remark,
              gpsId: this.isAll ? arrs.join(",") : this.receiveForm.gpsId
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.getDataList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    receiveHandle(row, flag) {
      this.receiveForm.recipient = "";
      this.receiveForm.remark = "";
      this.receiveForm.gpsId = row.id;
      console.log(this.receiveRule);
      if (flag) {
        this.isReceive = true;
        this.receiveRule.recipient[0].message = "领取人不能为空";
      } else {
        this.isReceive = false;
        this.receiveRule.recipient[0].message = "归还人不能为空";
      }
      this.visible = true;
    },

    // 批量领取
    recipientAll() {
      this.receiveForm.recipient = "";
      this.receiveForm.remark = "";
      this.isReceive = true;
      this.receiveRule.recipient[0].message = "领取人不能为空";
      this.visible = true;
    },

    changeUP(file, fileList) {
      //   console.log(file, fileList, "file, fileListfile, fileList");
      this.loadingUp = true;
      this.loadName = "导入中";
      if (file.name) {
        this.loadingUp = false;
        this.loadName = "导入";
      } else {
        this.loadingUp = false;
        this.loadName = "导入";
        this.$message.error("导入失败");
      }
    },

    // 上传安装包
    handleBaseUrlSuccess(response, file) {
      if (response.code == 0) {
        this.loadingUp = false;
        this.$message.success("导入成功");
        this.loadName = "导入";
        this.getDataList();
        this.$refs.upload.clearFiles();
      } else {
        this.$message.error(response.msg);
        this.loadName = "导入";
        this.loadingUp = false;
        this.$refs.upload.clearFiles();
      }
    },

    // 导入批量绑定
    batchBindingGPSSuccess(response) {
      if (response.code == 0) {
        this.$message.success("导入成功");
        this.getDataList();
        this.$refs.upload.clearFiles();
      } else {
        this.$message.error(response.msg);
        this.$refs.upload.clearFiles();
      }
    },
    // 下载GPS绑定模版
    downloadBindingExcel() {
      this.$http({
        url: this.$http.adornUrl("/sys/gps/management/downloadBindingExcel"),
        method: "get",
        responseType: "blob"
      }).then(({ data }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        let a = document.createElement("a");
        a.download = "GPS绑定模版.xlsx";
        a.href = URL.createObjectURL(blob);
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
      });
    },
    // 模板下载
    downloadTemplate() {
      this.$http({
        url: this.$http.adornUrl("/sys/gps/management/exportExcel"),
        method: "get",
        responseType: "blob"
      }).then(({ data }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        let a = document.createElement("a");
        a.download = "GPS模板.xlsx";
        a.href = URL.createObjectURL(blob);
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
      });
    },
    //导入模板
    importTemplate() {},
    // 获取数据列表
    getDataList() {
      let params = { ...this.pageParams, ...this.dataForm };
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/sys/gps/management/page"),
        method: "get",
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageParams.limit = val;
      this.pageParams.page = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageParams.page = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
      console.log(this.dataListSelections, "this.dataListSelections");
      // 批量领取
      this.isOk = val.some(item => {
        return item.status === 3;
      });
      // if (this.isOk === true) {
      //   this.$message({
      //     message: "不能选择已经归还的数据",
      //     type: "warning"
      //   });
      // }
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map(item => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$http({
          url: this.$http.adornUrl("/sys/gps/management/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.getDataList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    }
  }
};
</script>
